package com.tchhy.provider.rx

import io.reactivex.Observable
import io.reactivex.functions.Function
import retrofit2.HttpException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.util.concurrent.TimeUnit

/**
 * Describe: RxJava 重试相关
 *
 * Author: wfy
 *
 */
class RetryWithDelay(var maxRetries: Long = 0, var retryDelayMillis: Long = 0) : Function<Observable<out Throwable>, Observable<*>> {
    private var retryCount: Int = 0
    @Throws(Exception::class)
    override fun apply(t: Observable<out Throwable>): Observable<*> {
        return t.flatMap {
            it.printStackTrace()
            if (++retryCount <= maxRetries &&
                    (it is HttpException || it is SocketTimeoutException || it is ConnectException)) {
                return@flatMap Observable
                        .timer(retryDelayMillis,
                                TimeUnit.MILLISECONDS)
            }
            return@flatMap Observable.error<Throwable>(it)
        }
    }
}